package cn.xuexiluxian.open.quartz.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.xuexiluxian.open.common.annotation.Log;
import cn.xuexiluxian.open.common.annotation.RepeatSubmit;
import cn.xuexiluxian.open.common.constant.Constants;
import cn.xuexiluxian.open.common.controller.BaseController;
import cn.xuexiluxian.open.common.enums.BusinessType;
import cn.xuexiluxian.open.common.enums.ResultStatusCodeEnum;
import cn.xuexiluxian.open.common.response.ResponseResult;
import cn.xuexiluxian.open.common.utils.StringUtils;
import cn.xuexiluxian.open.quartz.entity.SystemJob;
import cn.xuexiluxian.open.quartz.service.SystemJobService;
import cn.xuexiluxian.open.quartz.util.CronUtils;
import cn.xuexiluxian.open.quartz.util.ScheduleUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 调度任务信息操作处理
 */
@RestController
@RequestMapping("task/job")
public class SystemJobController extends BaseController {
    @Autowired
    private SystemJobService systemJobService;

    /**
     * 查询定时任务列表
     */
    @GetMapping("page")
    @Log(title = "定时任务", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('task:job:list')")
    public ResponseResult Page(Page page, SystemJob bean) {
        page = systemJobService.pageList(page, bean);
        return ResponseResult.ok(page);
    }

    /**
     * 获取定时任务详细信息
     */
    @GetMapping(value = "get/{id}")
    @Log(title = "定时任务", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('task:job:query')")
    public ResponseResult getInfo(@PathVariable String id) {
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        return ResponseResult.ok(systemJobService.getById(id));
    }

    /**
     * 新增定时任务
     */
    @RepeatSubmit
    @PostMapping("add")
    @PreAuthorize("@permission.hasPermission('task:job:add')")
    @Log(title = "定时任务", businessType = BusinessType.INSERT)
    public ResponseResult add(@RequestBody SystemJob systemJob) throws SchedulerException {
        if (!CronUtils.isValid(systemJob.getCronExpression())) {
            return ResponseResult.error("新增任务'" + systemJob.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(systemJob.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return ResponseResult.error("新增任务'" + systemJob.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(systemJob.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            return ResponseResult.error("新增任务'" + systemJob.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(systemJob.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return ResponseResult.error("新增任务'" + systemJob.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(systemJob.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return ResponseResult.error("新增任务'" + systemJob.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(systemJob.getInvokeTarget())) {
            return ResponseResult.error("新增任务'" + systemJob.getJobName() + "'失败，目标字符串不在白名单内");
        }
        systemJob.setId(IdUtil.getSnowflakeNextIdStr());
        systemJob.setCreateBy(getCurrentUserId());
        systemJobService.insertJob(systemJob);
        return ResponseResult.ok();
    }

    /**
     * 修改定时任务
     */
    @RepeatSubmit
    @PostMapping("update")
    @PreAuthorize("@permission.hasPermission('task:job:update')")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    public ResponseResult update(@RequestBody SystemJob systemJob) throws SchedulerException {
        if(systemJob == null || StrUtil.isBlank(systemJob.getId())){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        if (!CronUtils.isValid(systemJob.getCronExpression())) {
            return ResponseResult.error("修改任务'" + systemJob.getJobName() + "'失败，Cron表达式不正确");
        } else if (StringUtils.containsIgnoreCase(systemJob.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return ResponseResult.error("修改任务'" + systemJob.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        } else if (StringUtils.containsAnyIgnoreCase(systemJob.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            return ResponseResult.error("修改任务'" + systemJob.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(systemJob.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return ResponseResult.error("修改任务'" + systemJob.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        } else if (StringUtils.containsAnyIgnoreCase(systemJob.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return ResponseResult.error("修改任务'" + systemJob.getJobName() + "'失败，目标字符串存在违规");
        } else if (!ScheduleUtils.whiteList(systemJob.getInvokeTarget())) {
            return ResponseResult.error("修改任务'" + systemJob.getJobName() + "'失败，目标字符串不在白名单内");
        }
        systemJob.setUpdateBy(getCurrentUserId());
        systemJobService.updateJob(systemJob);
        return ResponseResult.ok();
    }

    /**
     * 定时任务状态修改
     */
    @RepeatSubmit
    @PostMapping("changeStatus")
    @PreAuthorize("@permission.hasPermission('task:job:changeStatus')")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    public ResponseResult changeStatus(@RequestBody SystemJob systemJob) throws SchedulerException {
        if(systemJob == null || StrUtil.isBlank(systemJob.getId())){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        SystemJob newJob = systemJobService.getById(systemJob.getId());
        newJob.setStatus(systemJob.getStatus());
        systemJobService.changeStatus(newJob);
        return ResponseResult.ok();
    }

    /**
     * 定时任务立即执行一次
     */
    @RepeatSubmit
    @GetMapping("run/{id}")
    @PreAuthorize("@permission.hasPermission('task:job:run')")
    @Log(title = "定时任务", businessType = BusinessType.OTHER)
    public ResponseResult run(@PathVariable String id) throws SchedulerException {
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        systemJobService.run(id);
        return ResponseResult.ok();
    }

    /**
     * 删除定时任务
     */
    @RepeatSubmit
    @PostMapping("delete")
    @PreAuthorize("@permission.hasPermission('task:job:delete')")
    @Log(title = "定时任务", businessType = BusinessType.DELETE)
    public ResponseResult delete(@RequestBody List<String> ids) throws SchedulerException {
        if(ids == null || ids.size() <= 0){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        systemJobService.deleteJobByIds(ids);
        return ResponseResult.ok();
    }
}
